package com.wgworkshop.pems.controller;

import com.wgworkshop.pems.checkgroup.CreateCheckGroup;
import com.wgworkshop.pems.checkgroup.PatchCheckGroup;
import com.wgworkshop.pems.checkgroup.UpdateCheckGroup;
import com.wgworkshop.pems.common.ResponseData;
import com.wgworkshop.pems.model.HolidayModel;
import com.wgworkshop.pems.service.HolidayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 假期控制器。
 * Created by wlc on 2017/7/5.
 */
@RestController
@RequestMapping("holidays")
public class HolidayController {
    @Autowired
    private HolidayService holidayService;

    @PostMapping
    ResponseData<HolidayModel> create(@RequestBody @Validated(CreateCheckGroup.class) HolidayModel holidayModel) {
        HolidayModel resultModel = holidayService.save(holidayModel);
        return new ResponseData<HolidayModel>().success(resultModel);
    }

    @DeleteMapping("/{id}")
    ResponseData<Void> delete(@PathVariable("id") Long id) {
        holidayService.delete(id);
        return new ResponseData<Void>().success();
    }

    @PatchMapping("/{id}")
    ResponseData<HolidayModel> update(@PathVariable("id") Long id,
                                      @RequestBody @Validated(PatchCheckGroup.class) HolidayModel holidayModel) {
        HolidayModel resultModel = holidayService.update(id, holidayModel);
        return new ResponseData<HolidayModel>().success(resultModel);
    }

    @PutMapping
    ResponseData<HolidayModel> update(@RequestBody @Validated(UpdateCheckGroup.class) HolidayModel holidayModel) {
        HolidayModel resultModel = holidayService.update(holidayModel);
        return new ResponseData<HolidayModel>().success(resultModel);
    }

    @GetMapping("/{id}")
    ResponseData<HolidayModel> findOne(@PathVariable("id") Long id) {
        HolidayModel holidayModel = holidayService.findOne(id);
        return new ResponseData<HolidayModel>().success(holidayModel);
    }

    @GetMapping
    ResponseData<List<HolidayModel>> findByNameContaining(@RequestParam(name = "name", required = false) String name) {
        List<HolidayModel> holidayModels;
        if (name == null) {
            holidayModels = holidayService.findAll();
        } else {
            holidayModels = holidayService.findByNameContaining(name);
        }
        return new ResponseData<List<HolidayModel>>().success(holidayModels);
    }
}
